<?php 
class Silk_Mapi_Block_List extends Mage_Catalog_Block_Product_List
{
    protected function _getProductCollection()
    {
        //$this->setShowRootCategory(false);
        $categoryId = $this->getRequest()->getParam('category_id');
        if(!$categoryId) $categoryId = 12;
        $this->setCategoryId($categoryId);
        return parent::_getProductCollection();
    }

	/**
     * Need use as _prepareLayout - but problem in declaring collection from
     * another block (was problem with search result)
     */
    protected function _beforeToHtml()
    {
        $collection = $this->_getProductCollection();

        $collection->setPageSize(10)->setCurPage($this->getRequest()->getParam('page', 1));

        $keyword = $this->getRequest()->getParam('keyword');
        $sort = $this->getRequest()->getParam('sort');
        if(!$sort) $sort = 'desc';

        if($keyword)
        {
            $collection->addAttributeToFilter('name', array('like' => '%'.$keyword.'%'));
        }

        if($this->getCategoryId()==12 && $this->getRequest()->getParam('brand'))
        {
            $collection->addAttributeToFilter('brand', array('eq'=>$this->getRequest()->getParam('brand')));
        }

        if($sort)
        {
            $collection->getSelect()->
                joinLeft('sales_flat_order_item AS sfoi',
                'e.entity_id = sfoi.product_id',
                'SUM(sfoi.qty_ordered) AS ordered_qty')->group('e.entity_id')->order('ordered_qty ' . $sort);
        }


        Mage::dispatchEvent('catalog_block_product_list_collection', array(
            'collection' => $this->_getProductCollection()
        ));

        $this->_getProductCollection()->load();

        return Mage_Catalog_Block_Product_Abstract::_beforeToHtml();
    }
}